/* $RCSFile: MediaPlayerLib.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/MediaPlayerLib/MediaPlayerLib.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:56  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Settings.PageModules.MediaPlayerLib;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.MediaPlayerLib
{
 	#region Local TraceSwitch 
	public class MediaPlayerTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("MediaPlayerTrace","Special Trace Switch for MediaPlayerLib");
	}
	#endregion Local TraceSwitch 


    /// <summary>
    /// Initializer class for MediaPlayerLib 
    /// </summary>
    public class MediaPlayerLibSI : PortalModuleControlSI
    {
        MediaPlayerLibDB MediaPlayerDB		    =	new MediaPlayerLibDB();
        SortedList<string,string> lst           =   null;
        SortedList<string,string> Categories
        {
            get
            {
                if ( lst != null )
                    return lst;
                DataTable tb            =   MediaPlayerDB.GetMediaPlayerCategoriesGlobalized(Owner.ModuleID);
                lst                     =   new SortedList<string,string>();
                lst.Add(LocalizeHelper.Localize("MEDIAPLAYER_ALL_CATS","All"),"All");
                if ( MediaPlayerTrace.Sw.TraceError )
			        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib Categories GET Count: {0}.",tb.Rows.Count),MediaPlayerTrace.Sw.Info);
                foreach ( DataRow rw in tb.Rows )
                {
                    string cat          =   (string)rw["MDPCategory"];
                    if ( MediaPlayerTrace.Sw.TraceError )
			            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib Categories GET Cat: {0}.",cat),MediaPlayerTrace.Sw.Info);
                    if ( !lst.ContainsKey(cat) )
                        lst.Add(cat,cat);
                }
                return lst;
            }
        }

        public MediaPlayerLibSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MediaPlayerLibSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MediaPlayerLibSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MediaPlayerLibSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

			string extgrp                       =   pm.ExtendedResourcesGroup;
            
            ArrayList ar                        =   new ArrayList();
            ListItem it                         =   new ListItem(LocalizeHelper.Localize("MEDIA_SORTBY_ID","Id"),"MDPID");
            ar.Add(it);
            it                                  =   new ListItem(LocalizeHelper.Localize("MEDIA_SORTBY_CATEGORY","Category"),"MDPCategory");
            ar.Add(it);
            it                                  =   new ListItem(LocalizeHelper.Localize("MEDIA_SORTBY_TITLE","Title"),"MDPTitle");
            ar.Add(it);
            it                                  =   new ListItem(LocalizeHelper.Localize("MEDIA_SORTBY_CREATEDON","Created On"),"MDPCreatedDate");
            ar.Add(it);
            SettingItemSpecial SortBy	        =	new SettingItemSpecial("MEDIAPLAYER_SORTBY",new CustomListDataType(ar,"Text","Value"));
			SortBy.Required		                =	true;
			SortBy.Value			            =	"MDPCategory";
			SortBy.Order			            =	1;
			SortBy.ExtendedGroupName            =   extgrp;
            SortBy.Description	                =	"SortBy";
            SortBy.EnglishName	                =	"SortBy";
			bSettings.AddSetting(SortBy);
            
            CustomListDataType dttp             =   new CustomListDataType(null,"Key","Value");
            dttp.NeedDataEvent                  +=  new NeedDataEventHandler(dttp_NeedDataEvent);
            SettingItemSpecial SelectedCat	    =	new SettingItemSpecial("MEDIAPLAYER_SELECTEDCAT",dttp);
			SelectedCat.Required		        =	true;
			SelectedCat.Value			        =	"All";
			SelectedCat.Order			        =	10;
			SelectedCat.ExtendedGroupName       =   extgrp;
            SelectedCat.Description	            =	"Selected Category";
            SelectedCat.EnglishName	            =	"Selected Category";
			bSettings.AddSetting(SelectedCat);

			SettingItemSpecial showCategory	    =	new SettingItemSpecial("MEDIAPLAYER_SHOWCATEGORY",new BooleanDataType());
			showCategory.Value		            =	StStr.strTrue;       
			showCategory.Order		            =	20;
			showCategory.ExtendedGroupName      =   extgrp;
            showCategory.Description	        =	"Show Category";
            showCategory.EnglishName	        =	"Show Category";
			bSettings.AddSetting(showCategory);

			SettingItemSpecial showLength	    =	new SettingItemSpecial("MEDIAPLAYER_SHOWLENGTH",new BooleanDataType());
			showLength.Value		            =	StStr.strTrue;       
			showLength.Order		            =	30;
			showLength.ExtendedGroupName        =   extgrp;
            showLength.Description	            =	"Show Length";
            showLength.EnglishName	            =	"Show Length";
			bSettings.AddSetting(showLength);

			SettingItemSpecial showType	        =	new SettingItemSpecial("MEDIAPLAYER_SHOWTYPE",new BooleanDataType());
			showType.Value		                =	StStr.strTrue;       
			showType.Order		                =	40;
			showType.ExtendedGroupName          =   extgrp;
            showType.Description	            =	"Show Type";
            showType.EnglishName	            =	"Show Type";
			bSettings.AddSetting(showType);

			SettingItemSpecial showType2        =	new SettingItemSpecial("MEDIAPLAYER_SHOWTYPE2",new BooleanDataType());
			showType2.Value		                =	StStr.strTrue;       
			showType2.Order		                =	50;
			showType2.ExtendedGroupName         =   extgrp;
            showType2.Description	            =	"Show Video Type";
            showType2.EnglishName	            =	"Show Video Type";
			bSettings.AddSetting(showType2);

			SettingItemSpecial showDetail	    =	new SettingItemSpecial("MEDIAPLAYER_SHOWDETAIL",new BooleanDataType());
			showDetail.Value		            =	StStr.strTrue;       
			showDetail.Order		            =	60;
			showDetail.ExtendedGroupName        =   extgrp;
            showDetail.Description	            =	"Show Detail";
            showDetail.EnglishName	            =	"Show Detail";
			bSettings.AddSetting(showDetail);

            IntegerDataType pgsz                =   new IntegerDataType();
            pgsz.DecimalDigits                  =   0;
			SettingItemSpecial pageSize	        =	new SettingItemSpecial("MEDIAPLAYER_PAGESIZE",pgsz);
			pageSize.Value		                =	"4";       
			pageSize.Order		                =	70;
			pageSize.ExtendedGroupName          =   extgrp;
            pageSize.Description	            =	"Page size";
            pageSize.EnglishName	            =	"Page size";
			bSettings.AddSetting(pageSize);

            HtmlEditorDataType.AddEditorToSettings(bSettings, SettingItemGroup.MODULE_SPECIAL_SETTINGS,extgrp);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MediaPlayerLibSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }

        void dttp_NeedDataEvent(BaseDataType sender,EventArgs ev)
        {
            if ( MediaPlayerTrace.Sw.TraceError )
		        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib dttp_NeedDataEvent BEG sender: {0}.",sender),MediaPlayerTrace.Sw.Info);
            string SelVal                       =   sender.Val;
            ((ListDataType)sender).ResetDataSource(Categories,SelVal);
        }

    }

    public partial class MediaPlayerLib : PortalModuleControl 
    {
        MediaPlayerLibDB MediaPlayerDB		    =	new MediaPlayerLibDB();
		
        string _UploadDirectory =   string.Empty;
        string UploadDirectory
        {
            get
            {
                if ( _UploadDirectory != string.Empty )
                    return _UploadDirectory;
                _UploadDirectory        =   portalSettings.DefaultMediaVirtualPath;
                if ( !_UploadDirectory.EndsWith("/") )
                    _UploadDirectory    +=   "/";
               return _UploadDirectory;
            }
        }

        #region General Implementation
        /// <summary>
        /// GuidID 
        /// </summary>
		public override Guid GuidID 
		{
			get
			{
				return new Guid("{6FC1D24B-A2F4-409e-9630-0BF026955D30}");
			}
		}


		#endregion

        /// <summary>
        /// CTor
        /// </summary>
        public MediaPlayerLib() 
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MediaPlayerLib Ctor Called.",ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                 =   "MEDIAPLAYERLIB";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new MediaPlayerLibSI(bSettings,this);
        }
        
        public bool ShowCategory
        {
            get
            {
                return Settings["MEDIAPLAYER_SHOWCATEGORY"].ToBool();
            }
        }

        public bool ShowLength
        {
            get
            {
                return Settings["MEDIAPLAYER_SHOWLENGTH"].ToBool();
            }
        }

        public bool ShowType
        {
            get
            {
                return Settings["MEDIAPLAYER_SHOWTYPE"].ToBool();
            }
        }
        
        public bool ShowType2
        {
            get
            {
                return Settings["MEDIAPLAYER_SHOWTYPE2"].ToBool();
            }
        }

        public bool ShowDetail
        {
            get
            {
                return Settings["MEDIAPLAYER_SHOWDETAIL"].ToBool();
            }
        }

        public string GetType2(int type2)
        {
            switch ( type2 )
            {
                case 0:
                return LocalizeHelper.Localize("MEDIAPLAYER_TYPEWMV","Windows Media Video");
                case 1:
                return LocalizeHelper.Localize("MEDIAPLAYER_TYPESWF","Flash Video");
                default:
                return string.Format("Unknown-{0}",type2);
            }
        }

        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataSet of MediaPlayerUrl information from the MediaPlayerLib
        /// table, and then databind the results to a templated DataList
        /// server control.  It uses the AddonNice.MediaPlayerLibDB()
        /// data component to encapsulate all data functionality. 
        /// </summary>
        void MediaPlayerLib_Load(object sender, EventArgs e)
        {
            if ( MediaPlayerTrace.Sw.TraceError )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib MediaPlayerLib_Load BEG IsPostBack: {0}.",IsPostBack),MediaPlayerTrace.Sw.Info);
            // Set default Sort Order
            if ( !IsPostBack )
            {
                RadComboBoxItem it          =   ddListCat.Items.FindItemByValue(Settings["MEDIAPLAYER_SORTBY"].Value);
                if ( it != null )
                    it.Selected             =   true;
                RadDataPager1.PageSize      =   Settings["MEDIAPLAYER_PAGESIZE"].ToInt();
            }
            if ( MediaPlayerTrace.Sw.TraceError )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib MediaPlayerLib_Load END IsPostBack: {0}.",IsPostBack),MediaPlayerTrace.Sw.Info);
        }

        protected override void OnPreRender(EventArgs e)
        {
			string scriptString             =   "InitMDP();";
            if ( HasAjaxManager )
            {
                // We must execute this on end of page loading by browser
                if ( MediaPlayerTrace.Sw.TraceVerbose )
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]MediaPlayerLib OnPreRender script: {0}",scriptString),MediaPlayerTrace.Sw.Info);
                AjaxManager.ResponseScripts.Add(scriptString);
            }
            base.OnPreRender(e);
        }

        void VideoList_NeedDataSource(object sender,Telerik.Web.UI.RadListViewNeedDataSourceEventArgs e)
        {
			if ( MediaPlayerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MediaPlayerLib VideoList_NeedDataSource BEG RebindReason: {0}",e.RebindReason),MediaPlayerTrace.Sw.Info);
            // DataBind MediaPlayerLib to DataList Control
            try
            {
                DataTable Tb                    =   MediaPlayerDB.GetMediaPlayerLibGlobalized(ModuleID);
                DataView view                   =   Tb.DefaultView;
                if ( Settings["MEDIAPLAYER_SELECTEDCAT"].Value != "All" )
                {
                    view.RowFilter              =   string.Format("MDPCategory='{0}'",Settings["MEDIAPLAYER_SELECTEDCAT"].Value);
                }
                VideoList.DataSource            =   view;
            }
            catch ( Exception ex )
            {
                if ( MediaPlayerTrace.Sw.TraceError )
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib MediaPlayerLib_Load Time : {0}, ex : {1}",DateTime.UtcNow,ex),MediaPlayerTrace.Sw.Info);
                throw;
            }
			if ( MediaPlayerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MediaPlayerLib VideoList_NeedDataSource END RebindReason: {0}",e.RebindReason),MediaPlayerTrace.Sw.Info);
        }

        void VideoList_ItemDataBound(object sender,Telerik.Web.UI.RadListViewItemEventArgs e)
        {
			if ( MediaPlayerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MediaPlayerLib VideoList_ItemDataBound BEG item: {0}",e.Item),MediaPlayerTrace.Sw.Info);
			if ( e.Item.ItemType != RadListViewItemType.DataItem
				&& e.Item.ItemType != RadListViewItemType.SelectedItem 
				&& e.Item.ItemType != RadListViewItemType.EditItem 
				&& e.Item.ItemType != RadListViewItemType.AlternatingItem)
				return;
			try
			{
				LinkButton ctl				=	(LinkButton)e.Item.FindControl("ReadUrl");
				DataRowView di	            =   (DataRowView)((RadListViewDataItem)e.Item).DataItem;
                object ob                   =   di["MDPUrl"];
                string imageStr             =   string.Empty;
                if ( ob != null && !DBNull.Value.Equals(ob) )
                {
                    imageStr                =   (string)ob;
                    if ( !imageStr.StartsWith(UploadDirectory) && !imageStr.StartsWith("/") && !imageStr.StartsWith("~/") )
                        imageStr            =   UploadDirectory + imageStr;
                }
				string str					=	string.Format("javascript:SelectVideo('{0}');",imageStr);	
				ctl.Attributes.Add("href",str);
				}
			catch(Exception ex)
			{
				if ( MediaPlayerTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MediaPlayerLib myDataList_ItemDataBound ex : {0}",ex),MediaPlayerTrace.Sw.Info);
                throw;
			}
			if ( MediaPlayerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MediaPlayerLib VideoList_ItemDataBound END",MediaPlayerTrace.Sw.Info);
		}

        /// <summary>
        /// check the e.Value passed as an argument and fire sort command for the corresponding field. 
        /// The exact item in the listview from which you trigger the command is not important
        /// FireCommandEvent method invokes Rebind() implicitly, hence no explicit call is needed to refresh the listview
        /// </summary>
        void ddListCat_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( VideoList.Items.Count == 0 )
                return;
            switch (e.Value)
            {
                case "MDPID":
                case "MDPCategory":
                case "MDPTitle":
                case "MDPLength":
                case "MDPType":
                case "MDPType2":
                case "MDPCreatedDate":
                case "MDPModifiedDate":
                    VideoList.Items[0].FireCommandEvent(RadListView.SortCommandName, e.Value);
                    break;
                case "ClearSort":
                    VideoList.SortExpressions.Clear();
                    VideoList.Rebind();
                    break;
                default:
                    break;
            }
        }


        #region Std Overrides
		/// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        /// </summary>
        public override void Page_PreInit(object sender, EventArgs e)
        {
			this.AddUrl	= Config.ModulesPath+"/MediaPlayerLib/MediaPlayerLibEdit.aspx"; 
            base.Page_PreInit(sender, e);
        }

        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

        private void InitializeComponent() 
        {
            Load                            +=  new EventHandler(MediaPlayerLib_Load);
            VideoList.NeedDataSource        +=  new EventHandler<Telerik.Web.UI.RadListViewNeedDataSourceEventArgs>(VideoList_NeedDataSource);
            VideoList.ItemDataBound         +=  new EventHandler<Telerik.Web.UI.RadListViewItemEventArgs>(VideoList_ItemDataBound);
            ddListCat.SelectedIndexChanged  +=  new RadComboBoxSelectedIndexChangedEventHandler(ddListCat_SelectedIndexChanged);
            ddListCat.AutoPostBack          =   true;
		}

		#endregion

    }
}

